import { Component, OnInit, HostBinding } from '@angular/core';
import { trigger, transition, animate, style, state } from '@angular/animations';
import { ActivatedRoute, Router } from '@angular/router';

import { Home } from './home';
import { DialogService } from '../../shared/dialog.service';

@Component({
  template: `
    <div *ngIf="home">
      <h3>"{{editName}}"</h3>
      <div>
        <label>Id: </label>{{home.id}}
      </div>
      <div>
        <label>Name: </label>
        <input [(ngModel)]="editName" placeholder="name" />
      </div>
      <p>
        <button (click)="save()">保存</button>
        <button (click)="cancel()">取消</button>
      </p>
    </div>
  `,
  styles: ['input{width:20em}'],
  animations: [
    trigger('routeAnimation', [
      state('*',
        style({
          opacity: 1,
          transform: 'translateX(0)'
        })
      ),
      transition(':enter', [
        style({
          opacity: 0,
          transform: 'translateX(-100%)'
        }),
        animate('0.2s ease-in')
      ]),
      transition(':leave', [
        animate('0.5s ease-out', style({
          opacity: 0,
          transform: 'translateY(100%)'
        }))
      ])
    ])
  ]
})
export class HomeDetailComponent implements OnInit {
  @HostBinding('@routeAnimation') get routeAnimation() {
    return true;
  }

  @HostBinding('style.display') get display() {
    return 'block';
  }

  @HostBinding('style.position') get position() {
    return 'absolute';
  }

  public home: Home;
  public editName: string;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private dialogService: DialogService) { }

  public ngOnInit() {
    this.route.data
      .subscribe((data: { home: Home }) => {
        this.editName = data.home.name;
        this.home = data.home;
      });
  }

  public cancel() {
    this.gotoHome();
  }

  public save() {
    this.home.name = this.editName;
    this.gotoHome();
  }

  public canDeactivate(): Promise<boolean> | boolean {
    if (!this.home || this.home.name === this.editName) {
      return true;
    }
    return this.dialogService.confirm('放弃改变?');
  }

  public gotoHome() {
    const homeId = this.home ? this.home.id : null;
    this.router.navigate(['../', { id: homeId, foo: 'foo' }], { relativeTo: this.route });
  }

}
